<?php

namespace Addons\RedBag\Controller;

use Home\Controller\AddonsController;
use Admin\Builder\AdminListBuilder;
use Admin\Builder\AdminConfigBuilder;
use Admin\Builder\AdminTreeListBuilder;
use Think\Controller;

require_once(ONETHINK_ADDON_PATH . 'RedBag/Common/function.php');


class RedBagController extends AddonsController
{
    /**
     * 获取管理员配置参数
     */
    public function eject()
    {
        $field = D('Ucenter/Score')->getTypeList(array('status' => 1));
        $user=M('Member')->where(array('uid'=>is_login()))->find();

        foreach($field as &$v){
            $v['score']=$user['score'.$v['id']];
        };
        $this->assign("field", $field);
        $this->display(T('Addons://RedBag@RedBag/eject'));
    }


    /**
     * 对举报的信息进行数据库写入操作
     */
    public function sendRedBag()
    {
        $aContent = I('post.content', '', 'op_t');
        $aType = I('post.type', '', 'op_t');
        $aNum = I('post.num', '', 'op_t');
        $aAllmoney = I('post.allmoney', 0, 'op_t');
        $aOnemoney = I('post.onemoney', 0, 'op_t');
        $aRed_bag_type = I('post.red_bag_type', '', 'op_t');

        if($aAllmoney<0){
            $this->error('输入内容不能为负数');
        }
        if($aOnemoney<0){
            $this->error('输入内容不能为负数');
        }
        if($aNum<0){
            $this->error('红包个数不能为负');
        }
        if($aNum>100){
            $this->error('红包个数不能打大于100');
        }
        if(empty($aNum)){
            $this->error('请输入红包个数');
        }
        if($aAllmoney==0&&$aOnemoney==0){
        $this->error('请输入总额');
        }
        if(preg_match("/[\x7f-\xff]/", $aAllmoney)){
            $this->error('请输入数字');
        }
        if(preg_match("/[\x7f-\xff]/", $aOnemoney)){
            $this->error('请输入数字');
        }
        $data['uid'] = is_login();
        $data['num'] = $aNum;
        if ($aRed_bag_type == 1) {
            $data['all_money'] = $aOnemoney * $aNum;
            for ($i = 1; $i < $aNum; $i++) {
                $total =  $data['all_money'] - $aOnemoney*$i;
                $data['rank'][] =array($i,$aOnemoney,$total);
                }
            $data['rank'][] = array(intval($aNum), $total, 0);

        } else {
            $data['all_money'] = $aAllmoney;

            /*随机红包分配方法*/
            $total = $data['all_money'];//红包总额
            $num = $aNum;// 分成8个红包，支持8人随机领取
            $min = 0.01;//每个人最少能收到0.01元

            for ($i = 1; $i < $num; $i++) {
                $safe_total = ($total - ($num - $i) * $min) / ($num - $i);//随机安全上限
                $money = mt_rand($min * 100, $safe_total * 100) / 100;
                $total = $total - $money;
                $data['rank'][] = array($i, $money, $total);
                //   echo '第'.$i.'个红包：'.$money.' 元，余额：'.$total.' 元 <br/>';
            }
            $data['rank'][] = array(intval($num), $total, 0);
            //  echo '第'.$num.'个红包：'.$total.' 元，余额：0 元';
            /*随机红包分配方法END*/
            //$data['rank']=json_encode($data['rank'][]);
        }
        if (empty($aContent)) {
            $data['content'] = "恭喜发财，大吉大利！";
        } else {
            $data['content'] = $aContent;
        }
        $data['rank']= json_encode($data['rank']);
        $data['type'] = $aType;
        $data['redbag_type'] = $aRed_bag_type;
        $data['create_time'] = time();
        $data['status'] = 1;
        $field = D('Ucenter/Score')->getTypeList(array('status' => 1));
        foreach ($field as &$v) {
            if ($aType == $v['id']) {
                $user = D('Member')->where(array('uid' => is_login()))->find();
                if (($user['score' . $aType] - $data['all_money']) < 0) {
                    $this->error('你的' . $v['title'] . '不足，红包发送失败。');
                }
                $rs = D('Member')->where(array('uid' => is_login()))->setDec('score' . $v['id'], $data['all_money']);
                if ($rs) {
                    $res = M('Redbag')->add($data);
                    D('Message')->sendMessageWithoutCheckSelf(is_login(), '您发了个' . $v['title'] . '红包', $v['title'] . '减少了' . $data['all_money']);
                    action_log('send_redbag', 'redbag', $res, is_login());
                    if ($res) {
                        $redbag=M('Redbag')->where(array('id'=>$res))->find();
                       $this-> send_weibo("我发布了一个".$v['title']."红包【" . $data['content'] . "】：",'redbag',$redbag);
                       // D('Weibo/Weibo')->addWeibo(is_login(), "我发布了一个".$v['title']."红包【" . $data['content'] . "】：" ,'redbag',$redbag);
                        $this->success('红包发送成功！');
                    } else {
                        $this->error('红包发送失败！');
                    }

                }
            }
        }
    }

    public function openRedBag($param){

        parse_str($_GET['param'],$param);
        $this->assign('redbag',$param);
        $isGet=M('RedbagList')->where(array('redbagId'=>$param['id'],'uid'=>is_login()))->find();
        if($isGet){
            $this->assign('getRedBag',$isGet['get_bag']);
        }
        //判断是否已经领完了
        $countlist=M('RedbagList')->where(array('redbagId'=>$param['id']))->count();
        $redbag=M('Redbag')->where(array('id'=>$param['id']))->find();
        $this->assign('redbag',$redbag);
        $this->assign('redbagcount',$countlist);
        //获得单位
        $field = D('Ucenter/Score')->getTypeList(array('status' => 1));
        foreach ($field as &$v) {
            if ($redbag['type'] == $v['id']) {
                $this->assign('type_title',$v['title']);
                $this->assign('unit',$v['unit']);
            }
        }
        if($redbag['num']-$countlist==0){
        $this->assign('noRedbag',0);//红包已抢完
        }else{
            $this->assign('noRedbag',1);//红包未抢完
        }
        $getList=M('RedbagList')->where(array('redbagId'=>$param['id']))->order('create_time desc')->select();
        $getListType=M('Redbag')->where(array('id'=>$getList[0]['redbagId']))->field('type')->find();
        foreach($getList as &$v){
            $v['user']=query_user(array('uid', 'nickname', 'avatar64', 'space_url', 'rank_link', 'title'), $v['uid']);
            foreach ($field as &$k) {
                if($getListType['type']==$k['id']){
                    $v['type_title']=$k['title'];
                    $v['unit']=$k['unit'];
                }
            }
        }
        $this->assign('getList',$getList);
        $this->display(T('Addons://RedBag@RedBag/openredbag'));
    }


    public function doOpenRedBag(){
        if(!is_login()){
            $this->error('请先登录后操作');
        }
        $aId = I('post.redBagId', '', 'op_t');
        $redbag=M('Redbag')->where(array('id'=>$aId))->find();
        $senduesr=query_user(array('uid', 'nickname', 'avatar64', 'space_url', 'rank_link', 'title'), $redbag['uid']);
        $getuesr=query_user(array('uid', 'nickname', 'avatar64', 'space_url', 'rank_link', 'title'), is_login());
        $isGet=M('RedbagList')->where(array('redbagId'=>$aId,'uid'=>is_login()))->find();
        $countlist=M('RedbagList')->where(array('redbagId'=>$aId))->count();


        if($countlist>=$redbag['num']){
            $this->ajaxReturn(array('status'=>0,'info'=>'手慢了，红包已经抢完了~'));
        }
        if($isGet){
            $this->ajaxReturn(array('status'=>0,'info'=>'不能重复领取'));
        }else{
            $redbag['rank']=json_decode($redbag['rank'],true);
            $rank=M('RedbagList')->where(array('redbagId'=>$aId))->count()+1;//第几个领红包的。

            foreach( $redbag['rank'] as &$v){
                if($v[0]==$rank){
                    $data['get_bag']=$v[1];
                }
            }
            $data['redbagId']=$aId;
            $data['uid']=is_login();
            $data['create_time']=time();
            M('RedbagList')->add($data);
            M('Redbag')->where(array('id' => $aId))->setInc('sell_money', $data['get_bag']);
            $field = D('Ucenter/Score')->getTypeList(array('status' => 1));
            foreach ($field as &$v) {
                if ($redbag['type'] == $v['id']) {
                    $type_title=$v['title'];
                }
            }
            //判断是否已经领完了
            $redbag=M('Redbag')->where(array('id'=>$aId))->find();
            if($redbag['all_money']-$redbag['sell_money']<=0){ // 如果已经领完了，设置最佳手气者
                if($redbag['redbag_type']==2){
                    $listGet=M('RedbagList')->where(array('redbagId'=>$aId))->order('get_bag desc')->select();
                    M('RedbagList')->where(array('id'=>$listGet[0]['id']))->setField('best_luck',1);
                }else{
                    $listGet=M('RedbagList')->where(array('redbagId'=>$aId))->order('create_time asc')->select();
                    M('RedbagList')->where(array('id'=>$listGet[0]['id']))->setField('best_luck',2);
                }
            }

            foreach ($field as &$v) {
                if ($redbag['type'] == $v['id']) {
                    $rs = D('Member')->where(array('uid' => is_login()))->setInc('score' . $v['id'], $data['get_bag']);
                    if ($rs) {
                        action_log('get_redbag', 'redbag_list', $redbag['id'], is_login());
                        D('Message')->sendMessageWithoutCheckSelf(is_login(), '您领取了' . $senduesr['nickname'] . '的红包', $v['title'] . '增加了' . $data['get_bag']);
                        D('Message')->sendMessageWithoutCheckSelf($senduesr['uid'], $getuesr['nickname'].'领取了您的的红包',  '获得了' . $data['get_bag'].$v['title'] );
                        $this->ajaxReturn(array('status'=>1,'info'=>'领取成功获得'.$v['title'].$data['get_bag'],'getRedBag'=>$data['get_bag'],'type_title'=>$type_title));

                    }
                }
            }

        }
    }

    private function  send_weibo($content,$type,$feed_data = '', $from = ''){

    $uid = is_login();

   // D('Weibo/Topic')->addTopic($content);
    $weibo_id = D('Weibo/Weibo')->addWeibo($uid, $content, $type, $feed_data,$from);
    if (!$weibo_id) {
        return false;
    }
    action_log('add_weibo', 'weibo', $weibo_id, $uid);
    $uids = get_at_uids($content);
    send_at_message($uids, $weibo_id, $content);
    clean_query_user_cache(is_login(), array('weibocount'));
    return $weibo_id;

}

}